<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>添加课表</title>
    <link rel="stylesheet" href="/css/layui.css">
    <link rel="stylesheet" href="/scriptZIP/layui.min.css">
    <link rel="stylesheet" href="/css/item.css">
    <link rel="stylesheet" href="/scriptZIP/flatpickr.min.css">
    <link rel="stylesheet" href="/css/popup.css">
    <link rel="stylesheet" href="/css/eliminate_timetable.css">
    <style>
        .layui-input {
            text-align: center;
            line-height: 30px;
        }

        .del {
            display: inline-block;
            top: 5px;
        }

        .timetable-info {
            position: relative;
            padding-top: 20px;
        }
    </style>
</head>

<body>
    <div id="vue-root">
        <form enctype="multipart/form-data" id="form" ref="form" style="display: none;">
            <input type="file" name="file" id="file" @change="importExcel" ref="file"
                accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel">
        </form>

        <div class="install">
            <div class="timetable-class">
                <span>班级名称：</span>
                <select v-model="classId">
                    <option disabled="disabled" :value="null">请选择班级</option>
                    <option v-for="lesson in lessons" :key="lesson.id" :value="lesson.id" v-text="lesson.name"></option>
                </select>
            </div>
            <div class="timetable-class">
                <span>课表时间：</span>
                <flat-pickr name="date" v-model="date" :config="{locale:'zh'}"></flat-pickr>
            </div>
        </div>
        <div class="timetable" v-if="classId">
            <div v-if="able.add" style="margin-bottom: 10px;">
                <a href="/excel/lessontable.xls" class="layui-btn">下载导入模板</a>
                <label for="file" type="button" v-if="able.import" class="layui-btn">批量导入</label>
                <button class="layui-btn" @click="show=true">时段管理</button>
                <a :href="'eliminate_weekly.html?classId='+classId" class="layui-btn">添加按周循环的课程</a>
                <button class="layui-btn" @click="delTimes">删除今天之后的课时</button>
            </div>
            <div class="week" v-for="(day,index) in days" :key="index">
                <div class="weeks">
                    <p class="days"></p>
                    <div v-text="day.format('MM月DD日')" style="font-weight: bold;"></div>
                    <span v-text="day.format('dddd')"></span>
                </div>
                <div class="timetable-info" v-for="(o,index1) in list(day)">
                    <p class="del" @click="del(day,index1)" v-if="!past(day)">X</p>
                    <select class="choose-course" @change="doPeriod($event,o)" :value="toPeriod(o)">
                        <option disabled="disabled" :value="undefined">请选择时段</option>
                        <option v-if="toPeriod(o)&&!(toPeriod(o) in periodSet)" :value="toPeriod(o)">{{toPeriod(o)}}
                        </option>
                        <option v-for="period in periods" :key="period.id" :value="period.name" v-text="period.name">
                        </option>
                    </select>

                    <select class="choose-course" :disabled="past(day)" v-model="o.roomId">
                        <option disabled="disabled" :value="undefined">请选择教室</option>
                        <option v-for="room in rooms" :key="room.id" :value="room.id" v-text="room.name">
                        </option>
                    </select>
                    <select class="choose-course" :disabled="past(day)" v-model="o.teacherId">
                        <option disabled="disabled" :value="undefined">请选择教师</option>
                        <option v-for="teacher in teachers" :key="teachers.id" :value="teacher.id"
                            v-text="teacher.name">
                        </option>
                    </select>
                    <select class="choose-course" :disabled="past(day)" v-model="o.teacher1Id">
                        <option disabled="disabled" :value="undefined">请选择教师</option>
                        <option v-for="teacher in teachers" :key="teachers.id" :value="teacher.id"
                            v-text="teacher.name">
                        </option>
                    </select>
                    <select class="choose-course" :disabled="past(day)" v-model="o.teacher2Id">
                        <option disabled="disabled" :value="undefined">请选择教师</option>
                        <option v-for="teacher in teachers" :key="teachers.id" :value="teacher.id"
                            v-text="teacher.name">
                        </option>
                    </select>
                    <select class="choose-course" :disabled="past(day)" v-model="o.classesId">
                        <option disabled="disabled" :value="undefined">请选择课程</option>
                        <option v-for="related in relateds" :key="related.id" :value="related.id" v-text="related.name">
                        </option>
                    </select>
                    
                </div>
                <div class="timetable-info" v-if="!past(day)&&able.edit">
                    <button @click="add(day)">添加</button>
                </div>
            </div>

            <div class="layui-form-item" v-if="classId&&able.edit">
                <div class="layui-input-block">
                    <div class="offer" @click="submit">立即提交</div>
                </div>
            </div>
        </div>

        <div class="model-table5" v-show="show">
            <div class="popup">
                <div class="popup-title">课程时段</div>
                <div class="popup-center">
                    <div class="popup-box">
                        <div class="popup-time">
                            <div class="start-time" v-for="(period,index) in periods" :key="period.id">
                                <div class="layui-input name2" v-text="period.name"></div>
                                <span class="del" @click="delItem(index)">移除</span>
                            </div>
                        </div>
                        <div class="popup-time">
                            <div class="start-time">
                                <input class="layui-input name2 name" placeholder="请选择时段" id="period" v-model="period1">
                            </div>
                        </div>
                    </div>
                    <button class="sure" @click="submit1">确定</button>
                    <button class="back" @click="show=false">返回</button>
                </div>
            </div>
        </div>

    </div>

    <script src="/scriptZIP/qs.min.js"></script>
    <script src="/scriptZIP/vue.min.js"></script>
    <script src="/scriptZIP/axios.min.js"></script>

    <script src="/scriptZIP/dayjs.min.js"></script>
    <script src="/scriptZIP/zh-cn.min.js"></script>
    <script src="/scriptZIP/flatpickr.min.js"></script>
    <script src="/scriptZIP/zh.min.js"></script>


    <script src="/lib/vue-flatpickr.min.js"></script>

    <script src="/lib/laydate/laydate.js"></script>

    <script src="/js/common.js"></script>
    <script src="/js/auth_util.js"></script>

    <script>

        dayjs.locale('zh-cn');
        Vue.component('flat-pickr', VueFlatpickr);

        var schoolId = top_params().id;
        var agentId=localStorage.getItem('agentId')
        var today = dayjs(dayjs().format('YYYY-MM-DD'));

        var app = new Vue({
            el: '#vue-root',
            data: {
                classId: null,
                date: null,
                days: [],
                data: {},
                config: {
                    enableTime: true,
                    noCalendar: true,
                    dateFormat: 'H:i',
                    time_24hr: true,
                },
                lessons: [],
                rooms: [],
                relateds: [],//添加课程中的课程列表
                teachers: [],//添加课程中的老师列表
                able: {
                    add: false,
                    edit: false,
                    del: false
                },
                show: false,
                periods: [],
                period1: '',
                newPeriod: {
                    schoolId: schoolId
                }
            },
            created: function () {
                this.date = dayjs().add(1, 'day').format('YYYY-MM-DD');
                axios.get('/pc/classes/all/' + schoolId).then(function (res) {
                    this.lessons = res.data;
                }.bind(this));
                // axios.get('/pc/room/all/' + schoolId).then(function (res) {
                //     this.rooms = res.data;
                // }.bind(this));
                axios.get('/pc/lesson/period/' + schoolId).then(function (res) {
                    this.periods = res.data.map(function (it) {
                        return {
                            id: it.id,
                            name: it.startTime + ' - ' + it.endTime
                        };
                    });
                }.bind(this));
                abled('courseScheduling', this);
                if (sessionStorage.classId)
                    this.classId = sessionStorage.classId;
            },
            methods: {
                list: function (day) {
                    var date = day.format('YYYY-MM-DD');
                    if (date in this.data) return this.data[date];
                    return [];
                },
                past: function (day) {
                    return day.isBefore(today);
                },
                add: function (day) {
                    var date = day.format('YYYY-MM-DD');
                    if (date in this.data) {
                        this.data[date].push({});
                    } else {
                        Vue.set(this.data, date, [{}]);
                    }
                },
                submit: function () {
                    var list = this.toList();
                    list.forEach(function (it) {
                        console.log(it);
                        if (!(it.startTime && it.endTime && it.roomId)) {
                            alert('请检查' + it.date + '的数据是否填写完整');
                            throw it.date;
                        }
                        if (it.startTime >= it.endTime) {
                            alert('请检查' + it.date + '是否有课程开始时间晚于结束时间');
                            throw it.date;
                        }
                    });

                    axios.put('/pc/lesson/' + this.classId, list).then(function (res) {
                        alert('提交成功');
                    });
                },
                toList: function () {
                    var list = [];
                    for (var date in this.data) {
                        this.data[date].forEach(function (it) {
                            it.date = date;
                            list.push(it);
                        });
                        //调用重叠
                        this.checkOverlapped(this.data[date]);
                    }
                    return list;
                },
                checkOverlapped: function (list) {
                    list.sort(function (a, b) {
                        a = a.startTime + ',' + a.endTime;
                        b = b.startTime + ',' + b.endTime;
                        return a == b ? 0 : (a > b ? 1 : -1);
                    });
                    for (var i = 0; i < list.length - 1; i++) {
                        if (list[i].endTime > list[i + 1].startTime) {
                            alert(list[i].date + '存在时间段重叠');
                            throw '';
                        }
                    }
                },
                del: function (day, index) {
                    if (confirm('确认删除？'))
                        this.list(day).splice(index, 1);
                },
                importExcel: function () {
                    var path = this.$refs.file.value;
                    if (!path.endsWith('.xls') && !path.endsWith('.xlsx')) {
                        alert('请选择.xls或.xlsx文件');
                        return;
                    }
                    axios.post('/pc/lesson/time/import/' + this.classId, new FormData(this.$refs.form)).then(function () {
                        this.getData();
                        alert('成功');
                        this.$refs.file.value = '';
                    }.bind(this)).catch(function () {
                        this.$refs.file.value = '';
                    }.bind(this));
                },
                getData: function () {
                    if (!this.classId) return;
                    axios.get('/pc/lesson/time/' + this.classId).then(function (res) {
                        this.data = res.data;
                    }.bind(this));
                },
                getData2: function () {
                    if (!this.classId) return;
                    axios.get('/pc/classes/' + this.classId).then(function (res) {

                        // axios.get('/pc/teacher/all/' + schoolId).then(function (res1) {
                        //     var arr = []
                        //     res1.data.forEach(item => {
                        //         if (item.id == res.data.teacherId) {
                        //             arr.push(item)
                        //         }
                        //     });
                        //     this.teachers = arr
                           // 修改后：获取授课老师（多个教师）
        if (res.data.personCharge && res.data.personCharge.length > 0) {
            // 如果班级有配置授课老师，获取这些特定的授课老师
            axios.get('/pc/teacher/all/' + schoolId).then(function (res1) {
                var arr = []
                res1.data.forEach(item => {
                    // 检查该老师是否在授课老师数组中
                    if (res.data.personCharge.includes(item.id)) {
                        arr.push(item)
                    }
                });
                this.teachers = arr;
            }.bind(this));
        } else {
            // 如果没有配置授课老师，获取所有老师
            axios.get('/pc/teacher/all/' + schoolId).then(function (res1) {
                this.teachers = res1.data;
            }.bind(this));
        }
                       
                        axios.get('/pc/room/all/' + schoolId).then(function (res1) {
                            var arr = []
                            res1.data.forEach(item => {
                                if (item.id == res.data.classroom) {
                                    arr.push(item)
                                }
                            });
                            this.rooms = arr
                        }.bind(this));
                        axios.get('/pc/course/all/' +agentId ).then(function (res1) {
                            console.log(res1.data, '课程');
                            var arr = []
                            res1.data.forEach(item => {
                                if (item.id == res.data.related) {
                                    arr.push(item)
                                }
                            });
                            this.relateds = arr;
                        }.bind(this));
                    }.bind(this));
                },
                delItem: function (index) {
                    axios.delete('/pc/lesson/period/' + this.periods[index].id,).then(function (res) {
                        this.periods.splice(index, 1);
                    }.bind(this));
                },
                submit1: function () {
                    if (!this.period1) {
                        alert('请选择时段');
                        return;
                    }
                    axios.post('/pc/lesson/period', this.newPeriod).then(function (res) {
                        this.periods.push({ name: this.period1, id: res.data });
                        this.period1 = '';
                    }.bind(this));
                },
                toPeriod: function (lesson) {
                    if (lesson.startTime && lesson.endTime)
                        return lesson.startTime + ' - ' + lesson.endTime;
                },
                doPeriod: function (event, lesson) {
                    var a = event.target.value.split(' - ');
                    lesson.startTime = a[0];
                    lesson.endTime = a[1];
                },
                delTimes: function () {
                    if (!confirm('确认删除本课程今天之后的所有课时吗？')) return;
                    axios.delete('/pc/lesson/times/' + this.classId).then(function (res) {
                        this.getData();
                        alert('成功');
                    }.bind(this));
                }
            },
            computed: {
                periodSet: function () {
                    var o = {};
                    this.periods.forEach(function (it) {
                        o[it.name] = true;
                    }.bind(this));
                    return o;
                }
            },
            watch: {
                date: function (newValue, oldValue) {
                    var date = dayjs(newValue);
                    var days = [];
                    for (var i = 0; i < 7; i++)
                        days.push(date.day(i));
                    this.days = days;
                },
                classId: function (newValue, oldValue) {
                    sessionStorage.classId = newValue;
                    this.getData();
                    this.getData2();
                }
            }
        });

        laydate.render({
            elem: '#period',
            type: 'time',
            format: 'HH:mm',
            range: true,
            done: function (value, date, endDate) {
                app.period1 = value;
                var a = value.split(' - ');
                app.newPeriod.startTime = a[0];
                app.newPeriod.endTime = a[1];
            }
        });

    </script>

</body>

</html>